<template>
  <NavBar></NavBar>
  <div class="finance-container">
    <div class="finance-box">
      <div class="finance-title">经济情况</div>
      
      <!-- 总览区域 -->
      <div class="overview-section">
        <el-card class="overview-card">
          <template #header>
            <div class="card-header">
              <span>财务总览</span>
            </div>
          </template>
          <div class="overview-stats">
            <div class="stat-item">
              <div class="stat-value">¥{{ formatNumber(totalRevenue) }}</div>
              <div class="stat-label">总收入</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">¥{{ formatNumber(totalCost) }}</div>
              <div class="stat-label">总成本</div>
            </div>
            <div class="stat-item" :class="{'profit': totalProfit >= 0, 'loss': totalProfit < 0}">
              <div class="stat-value">¥{{ formatNumber(totalProfit) }}</div>
              <div class="stat-label">总利润</div>
            </div>
          </div>
        </el-card>
      </div>
      
      <!-- 牛只财务区域 -->
      <div class="cattle-finance-section">
        <el-tabs type="border-card">
          <el-tab-pane label="在栏牛只">
            <div v-loading="loading">
              <el-table :data="activeCattle" style="width: 100%">
                <el-table-column prop="id" label="ID" width="200" />
                <el-table-column prop="name" label="牛只名称" width="200" />
                <el-table-column prop="earTag" label="耳标" width="200" />
                <el-table-column prop="additionReason" label="获得原因" width="200" />
                <el-table-column prop="createdAt" label="添加日期" width="200">
                  <template #default="{row}">
                    {{ formatDate(row.createdAt) }}
                  </template>
                </el-table-column>
                <el-table-column prop="totalCost" label="成本" width="200">
                  <template #default="{row}">
                    <span class="cost">¥{{ formatNumber(row.cost) }}</span>
                  </template>
                </el-table-column>
              </el-table>
              <div class="summary-row">
                <span>在栏牛只总成本: </span>
                <span class="cost">¥{{ formatNumber(activeCattleTotalCost) }}</span>
              </div>
            </div>
          </el-tab-pane>
          
          <el-tab-pane label="已出栏牛只">
            <div v-loading="loading">
              <el-table :data="soldCattle" style="width: 100%">
                <el-table-column prop="id" label="ID" width="80" />
                <el-table-column prop="additionReason" label="获得原因" width="150" />
                <el-table-column prop="deletionReason" label="出栏原因" width="150" />
                <el-table-column prop="createdAt" label="添加日期" width="180">
                  <template #default="{row}">
                    {{ formatDate(row.createdAt) }}
                  </template>
                </el-table-column>
                <el-table-column prop="deletedAt" label="出栏日期" width="180">
                  <template #default="{row}">
                    {{ formatDate(row.deletedAt) }}
                  </template>
                </el-table-column>
                <el-table-column prop="cost" label="成本" width="120">
                  <template #default="{row}">
                    <span class="cost">¥{{ formatNumber(row.cost) }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="revenue" label="收入" width="120">
                  <template #default="{row}">
                    <span class="revenue">¥{{ formatNumber(row.revenue) }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="profit" label="利润" width="120">
                  <template #default="{row}">
                    <span :class="{'profit': row.profit >= 0, 'loss': row.profit < 0}">
                      ¥{{ formatNumber(row.profit) }}
                    </span>
                  </template>
                </el-table-column>
              </el-table>
              <div class="summary-row">
                <span>已出栏牛只总利润: </span>
                <span :class="{'profit': soldCattleTotalProfit >= 0, 'loss': soldCattleTotalProfit < 0}">
                  ¥{{ formatNumber(soldCattleTotalProfit) }}
                </span>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
      
      <!-- 疾病治疗费用区域 -->
      <div class="sickness-finance-section">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>疾病治疗费用</span>
            </div>
          </template>
          <div v-loading="loading">
            <el-table :data="sicknessRecords" style="width: 100%">
              <el-table-column prop="cattleId" label="牛只ID" width="200" />
              <el-table-column prop="diseaseName" label="疾病名称" width="200" />
              <el-table-column prop="startDate" label="发病日期" width="250">
                <template #default="{row}">
                  {{ formatDate(row.startDate) }}
                </template>
              </el-table-column>
              <el-table-column prop="endDate" label="康复日期" width="180">
                <template #default="{row}">
                  {{ row.endDate ? formatDate(row.endDate) : '治疗中' }}
                </template>
              </el-table-column>
              <el-table-column prop="cost" label="治疗费用" width="120">
                <template #default="{row}">
                  <span class="cost">¥{{ formatNumber(row.cost) }}</span>
                </template>
              </el-table-column>
            </el-table>
            <div class="summary-row">
              <span>疾病治疗总费用: </span>
              <span class="cost">¥{{ formatNumber(sicknessTotalCost) }}</span>
            </div>
          </div>
        </el-card>
      </div>
      
      <!-- 其他财务记录区域 -->
      <div class="other-finance-section">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>其他财务记录</span>
              <el-button class="button" type="primary" @click="showAddOtherFinanceDialog">
                添加记录
              </el-button>
            </div>
          </template>
          <div v-loading="loading">
            <el-table :data="otherFinanceRecords" style="width: 100%">
              <el-table-column prop="id" label="ID" width="80" />
              <el-table-column prop="description" label="描述" width="200" />
              <el-table-column prop="detailedDescription" label="详细描述" />
              <el-table-column prop="createdAt" label="添加日期" width="180"/>
              <el-table-column prop="amount" label="金额" width="150">
                <template #default="{row}">
                  <span :class="{'revenue': row.amount > 0, 'cost': row.amount < 0}">
                    ¥{{ formatNumber(row.amount) }}
                  </span>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="120">
                <template #default="{row}">
                  <el-button type="danger" size="small" @click="deleteOtherFinance(row.id)">
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <div class="summary-row">
              <span>其他财务记录总额: </span>
              <span :class="{'profit': otherFinanceTotalAmount >= 0, 'loss': otherFinanceTotalAmount < 0}">
                ¥{{ formatNumber(otherFinanceTotalAmount) }}
              </span>
            </div>
          </div>
        </el-card>
      </div>
    </div>
  </div>
  
  <!-- 添加其他财务记录对话框 -->
  <el-dialog
    v-model="addOtherFinanceDialogVisible"
    title="添加其他财务记录"
    width="500px"
  >
    <el-form :model="newOtherFinance" label-width="120px">
      <el-form-item label="描述" required>
        <el-input v-model="newOtherFinance.description" placeholder="请输入描述" />
      </el-form-item>
      <el-form-item label="详细描述">
        <el-input
          v-model="newOtherFinance.detailedDescription"
          type="textarea"
          rows="3"
          placeholder="请输入详细描述"
        />
      </el-form-item>
      <el-form-item label="金额" required>
        <el-input-number
          v-model="newOtherFinance.amount"
          :precision="2"
          :step="100"
          :min="-1000000"
          :max="1000000"
        />
        <div class="amount-hint">提示: 正数表示收入，负数表示支出</div>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="addOtherFinanceDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleAddOtherFinance" :loading="submitting">
          确认
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue';
import { useStore } from 'vuex';
import { ElMessage, ElMessageBox } from 'element-plus';
import NavBar from '@/components/NavBar.vue';

export default {
  name: 'CattleFinance',
  components: { NavBar },
  setup() {
    const store = useStore();
    const loading = ref(false);
    const submitting = ref(false);
    
    // 数据
    const activeCattle = ref([]);
    const soldCattle = ref([]);
    const sicknessRecords = ref([]);
    const otherFinanceRecords = ref([]);
    
    // 其他财务记录对话框
    const addOtherFinanceDialogVisible = ref(false);
    const newOtherFinance = reactive({
      description: '',
      detailedDescription: '',
      amount: 0
    });
    
    // 计算总成本、总收入和总利润
    const activeCattleTotalCost = computed(() => {
      return activeCattle.value.reduce((sum, cattle) => {
        return sum + cattle.cost + (cattle.sicknessCost || 0);
      }, 0);
    });
    
    const soldCattleTotalProfit = computed(() => {
      return soldCattle.value.reduce((sum, cattle) => {
        return sum + cattle.profit;
      }, 0);
    });
    
    const sicknessTotalCost = computed(() => {
      return sicknessRecords.value.reduce((sum, record) => {
        return sum + (record.cost || 0);
      }, 0);
    });
    
    const otherFinanceTotalAmount = computed(() => {
      return otherFinanceRecords.value.reduce((sum, record) => {
        return sum + record.amount;
      }, 0);
    });
    
    // 修改总成本计算，包含疾病治疗费用
    const totalCost = computed(() => {
      return activeCattleTotalCost.value + 
        soldCattle.value.reduce((sum, cattle) => sum + cattle.cost, 0) +
        sicknessTotalCost.value + // 添加疾病治疗总费用
        otherFinanceRecords.value.reduce((sum, record) => sum + (record.amount < 0 ? -record.amount : 0), 0);
    });
    
    const totalRevenue = computed(() => {
      return soldCattle.value.reduce((sum, cattle) => sum + cattle.revenue, 0) +
        otherFinanceRecords.value.reduce((sum, record) => sum + (record.amount > 0 ? record.amount : 0), 0);
    });
    
    // 修改总利润计算，考虑疾病治疗费用
    const totalProfit = computed(() => {
      return totalRevenue.value - totalCost.value;
    });
    
    // 格式化数字
    const formatNumber = (num) => {
      return num.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
    };
    
    // 格式化日期
    const formatDate = (dateStr) => {
      if (!dateStr) return '';
      const date = new Date(dateStr);
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
    };
    
    
    const fetchActiveCattle = async () => { 
        loading.value = true; 
        // 获取在栏牛只 
        await store.dispatch('fetchCattleList', { 
          token: store.state.user.token, 
          success: (resp) => { 
            // 处理获取到的在栏牛只数据
            activeCattle.value = resp.data.map(cattle => {
              return {
                ...cattle,
                id: cattle.id,
                name: cattle.name,
                earTag: cattle.earTag,
                additionReason: cattle.additionReason,
                createdAt: cattle.createdAt,
                cost: cattle.cost || 0
              };
            });
          }, 
          error: (err) => { 
            ElMessage.error('获取在栏牛只数据失败'); 
            console.error(err); 
          } 
        }); 
    };
    
    // 获取已出栏牛只数据
    const fetchSoldCattle = async () => {
      try {
        loading.value = true;
        const resp = await store.dispatch('fetchAllCattleList', {
          token: store.state.user.token
        });
        
        if (resp && resp.status === 'success') {
          // 过滤出已出栏的牛只
          soldCattle.value = resp.data.filter(cattle => cattle.isDeleted).map(cattle => ({
            ...cattle,
            profit: (cattle.revenue || 0) - cattle.cost
          }));
        }
      } catch (error) {
        ElMessage.error('获取已出栏牛只数据失败');
        console.error(error);
      } finally {
        loading.value = false;
      }
    };
    
    // 获取疾病治疗记录 - 直接使用fetchAllSicknessHistory
    const fetchSicknessRecords = async () => {
      try {
        loading.value = true;
        const resp = await store.dispatch('fetchAllSicknessHistory', {
          token: store.state.user.token
        });
        
        if (resp && resp.status === 'success') {
          sicknessRecords.value = resp.data;
        }
      } catch (error) {
        ElMessage.error('获取疾病治疗记录失败');
        console.error(error);
      } finally {
        loading.value = false;
      }
    };
    
    // 获取其他财务记录
    const fetchOtherFinanceRecords = async () => {
      try {
        loading.value = true;
        const resp = await store.dispatch('fetchOtherFinanceRecords', {
          token: store.state.user.token
        });
        
        if (resp && resp.status === 'success') {
          otherFinanceRecords.value = resp.data;
        }
      } catch (error) {
        ElMessage.error('获取其他财务记录失败');
        console.error(error);
      } finally {
        loading.value = false;
      }
    };
    
    // 显示添加其他财务记录对话框
    const showAddOtherFinanceDialog = () => {
      addOtherFinanceDialogVisible.value = true;
      newOtherFinance.description = '';
      newOtherFinance.detailedDescription = '';
      newOtherFinance.amount = 0;
    };
    
    // 添加其他财务记录
    const handleAddOtherFinance = async () => {
      if (!newOtherFinance.description) {
        ElMessage.warning('请输入描述');
        return;
      }
      
      try {
        submitting.value = true;
        const resp = await store.dispatch('addOtherFinanceRecord', {
          token: store.state.user.token,
          record: newOtherFinance
        });
        
        if (resp && resp.status === 'success') {
          ElMessage.success('添加财务记录成功');
          addOtherFinanceDialogVisible.value = false;
          await fetchOtherFinanceRecords();
        }
      } catch (error) {
        ElMessage.error('添加财务记录失败');
        console.error(error);
      } finally {
        submitting.value = false;
      }
    };
    
    // 删除其他财务记录
    const deleteOtherFinance = async (id) => {
      try {
        await ElMessageBox.confirm('确定要删除这条财务记录吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        
        loading.value = true;
        const resp = await store.dispatch('deleteOtherFinanceRecord', {
          token: store.state.user.token,
          id: id
        });
        
        if (resp && resp.status === 'success') {
          ElMessage.success('删除财务记录成功');
          await fetchOtherFinanceRecords();
        }
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除财务记录失败');
          console.error(error);
        }
      } finally {
        loading.value = false;
      }
    };
    
    // 页面加载时获取数据
    onMounted(async () => {
      loading.value = true;
      try {
        // 按顺序获取各类数据
        await fetchSicknessRecords(); // 先获取所有疾病记录
        await fetchActiveCattle();
        await fetchSoldCattle();
        await fetchOtherFinanceRecords();
      } catch (error) {
        console.error('初始化数据失败:', error);
      } finally {
        loading.value = false;
      }
    });
    
    return {
      loading,
      submitting,
      activeCattle,
      soldCattle,
      sicknessRecords,
      otherFinanceRecords,
      activeCattleTotalCost,
      soldCattleTotalProfit,
      sicknessTotalCost,
      otherFinanceTotalAmount,
      totalCost,
      totalRevenue,
      totalProfit,
      formatNumber,
      formatDate,
      addOtherFinanceDialogVisible,
      newOtherFinance,
      showAddOtherFinanceDialog,
      handleAddOtherFinance,
      deleteOtherFinance
    };
  }
};
</script>

<style scoped>
.finance-container {
  display: flex;
  justify-content: center;
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;

}

.finance-box {
  width: 90%;
  background-color: white;
  padding: 30px;
  border-radius: 12px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  margin-bottom: 30px; /* 添加底部边距 */
  overflow-y: auto; /* 添加垂直滚动 */
  max-height: 90vh;
}

.finance-title {
  text-align: center;
  font-size: 24px;
  margin-bottom: 20px;
  color: #409eff;
  font-weight: 600;
}

.overview-section,
.cattle-finance-section,
.sickness-finance-section,
.other-finance-section {
  margin-bottom: 30px;
}

.overview-stats {
  display: flex;
  justify-content: space-around;
  padding: 20px 0;
}

.stat-item {
  text-align: center;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #606266;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.summary-row {
  margin-top: 15px;
  text-align: right;
  font-weight: bold;
  font-size: 16px;
  padding-right: 20px;
}

.cost {
  color: #f56c6c;
}

.revenue {
  color: #67c23a;
}

.profit {
  color: #67c23a;
}

.loss {
  color: #f56c6c;
}

.amount-hint {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

@media (max-width: 768px) {
  .finance-box {
    width: 95%;
    padding: 15px;
  }
  
  .overview-stats {
    flex-direction: column;
    gap: 15px;
  }
}

/* 修改表格样式，移除固定高度限制 */
.el-table {
  max-height: none !important; /* 覆盖可能的最大高度限制 */
}

/* 确保页面主体可滚动 */
html, body {
  height: 100%;
  margin: 0;
  padding: 0;
  overflow-y: auto;
}

@media (max-width: 768px) {
  .finance-box {
    width: 95%;
    padding: 15px;
  }
  
  .overview-stats {
    flex-direction: column;
    gap: 15px;
  }
}
</style>